package zhongbo.java.air.flightpath.web.websocket;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat1")
@Component
@Slf4j
public class ChatWebsocket {


    public final static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void openConn(Session session, @PathParam("userId")String userId) {
        String sessionId = session.getId();
        System.out.println("建立ws连接: " + sessionId);
        sessionMap.put(sessionId, session);
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        String sessionId = session.getId();
        String reasonPhrase = reason.getReasonPhrase();
        System.out.println(String.format("关闭ws连接: %s, reason: %s", sessionId, reasonPhrase));
        sessionMap.remove(sessionId);
    }

    @OnMessage
    public void echoTextMessage(Session session, String msg, boolean last, @PathParam("userId") String userId) {
        if (session.isOpen()) {
            System.out.println("收到消息" + msg);
            sessionMap.values().forEach(s -> {
                try {
                    s.getBasicRemote().sendText(msg);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

//    @OnError
//    public void onError(Session)
}